/**
 * StoreApiDirectTest - 直接测试门店API接口
 * 
 * 该测试文件用于直接测试门店API接口的连通性和数据获取功能
 * 验证能否正常获取门店数据，特别是id=14的南京门店数据
 * 
 * 功能：
 * - 测试门店API接口连通性
 * - 验证数据格式和内容
 * - 检查网络配置是否正确
 */

package com.example.brain_wave.test.store_room

import com.example.brain_wave.bluetooth.api.StoreRoomApiClient
import com.example.brain_wave.bluetooth.model.Store
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.delay
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import java.util.concurrent.TimeUnit

class StoreApiDirectTest {
    
    private val baseUrl = "http://192.168.2.3:8000"
    private val endpoint = "/admin/store/apiStores"
    private val token = "jsw2hSS8ypfheSX5"
    private val server = "1"
    
    fun testDirectApiCall() {
        println("=== 开始测试门店API接口 ===")
        
        val client = OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build()
        
        val url = "$baseUrl$endpoint?token=$token&server=$server"
        println("请求URL: $url")
        
        val request = Request.Builder()
            .url(url)
            .get()
            .addHeader("Accept", "application/json")
            .addHeader("Content-Type", "application/json")
            .build()
        
        try {
            val response: Response = client.newCall(request).execute()
            println("响应状态码: ${response.code}")
            println("响应消息: ${response.message}")
            
            if (response.isSuccessful) {
                val responseBody = response.body?.string()
                println("响应内容: $responseBody")
                
                // 检查是否包含南京门店数据
                if (responseBody?.contains("南京门店") == true) {
                    println("✓ 成功找到南京门店数据")
                } else {
                    println("✗ 未找到南京门店数据")
                }
                
                // 检查是否包含id=14的数据
                if (responseBody?.contains("\"id\":14") == true || responseBody?.contains("\"id\": 14") == true) {
                    println("✓ 成功找到id=14的数据")
                } else {
                    println("✗ 未找到id=14的数据")
                }
                
            } else {
                println("✗ API请求失败")
                val errorBody = response.body?.string()
                println("错误内容: $errorBody")
            }
            
            response.close()
            
        } catch (e: IOException) {
            println("✗ 网络请求异常: ${e.message}")
            e.printStackTrace()
        } catch (e: Exception) {
            println("✗ 其他异常: ${e.message}")
            e.printStackTrace()
        }
        
        println("=== 门店API测试完成 ===")
    }
    
    fun testWithStoreRoomApiClient() {
        println("\n=== 使用StoreRoomApiClient测试 ===")
        
        // 创建模拟Context（在实际测试中应该使用真实的Context）
        // 这里为了演示目的，我们跳过Context相关的测试
        println("注意：此测试需要真实的Android Context才能运行")
        println("在实际Android测试环境中，应该使用:")
        println("val context = ApplicationProvider.getApplicationContext<Context>()")
        println("val apiClient = StoreRoomApiClient(context)")
        
        return // 暂时跳过此测试，因为需要Android Context
        
        var receivedStores: List<Store>? = null
        var hasError = false
        var errorMessage: String? = null
        
        apiClient.setOnStoreListReceived { stores ->
            receivedStores = stores
            println("✓ 成功接收到门店列表，数量: ${stores.size}")
            stores.forEach { store ->
                println("门店: id=${store.id}, name=${store.name}")
                if (store.id == 14 && store.name.contains("南京")) {
                    println("✓ 找到目标门店: id=14, name=${store.name}")
                }
            }
        }
        
        apiClient.setOnError { error ->
            hasError = true
            errorMessage = error
            println("✗ API客户端错误: $error")
        }
        
        // 发起请求
        apiClient.getStoreList()
        
        // 等待响应（最多等待10秒）
        runBlocking {
            var waitTime = 0
            while (receivedStores == null && !hasError && waitTime < 10000) {
                delay(100)
                waitTime += 100
            }
        }
        
        if (receivedStores == null && !hasError) {
            println("✗ 请求超时，未收到响应")
        }
        
        println("=== StoreRoomApiClient测试完成 ===")
    }
}

// 主函数用于运行测试
fun main() {
    val test = StoreApiDirectTest()
    test.testDirectApiCall()
    test.testWithStoreRoomApiClient()
}